package com.stark.dzb.libs;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.hjq.bar.TitleBar;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import stark.common.basic.base.BaseTitleBarFragmentActivity;
import stark.common.basic.constant.Extra;
import stark.common.basic.utils.IntentUtil;

/**
 * Author：daizhongbin on 2021/7/29
 * Email：1027154338@qq.com
 * Desc:
 */
public class BaseWithFragmentActivity extends BaseTitleBarFragmentActivity {

    public static void start(Context context, Class<? extends BaseWithFragmentActivity> activityClass,
                             Class<? extends Fragment> fragmentClass) {
        Intent intent = IntentUtil.getIntent(context, activityClass);
        intent.putExtra(Extra.CONTENT, fragmentClass);
        context.startActivity(intent);
    }

    public static void start(Context context, String title, Class<? extends Fragment> fragmentClass) {
        start(context, title, fragmentClass, null);
    }

    public static void start(Context context, String title, Class<? extends Fragment> fragmentClass, Bundle fragmentArgument) {
        Intent intent = IntentUtil.getIntent(context, BaseWithFragmentActivity.class);
        intent.putExtra(Extra.CONTENT, fragmentClass);
        intent.putExtra(Extra.TITLE, title);
        if (fragmentArgument != null) {
            intent.putExtras(fragmentArgument);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onConfigTitleBar(TitleBar titleBar) {
        super.onConfigTitleBar(titleBar);
        Intent intent = getIntent();
        String title = null;
        if (intent != null) {
            title = intent.getStringExtra(Extra.TITLE);
        }
        if (!TextUtils.isEmpty(title)) {
            titleBar.setTitle(title);
        }
    }

    @NonNull
    @Override
    protected Fragment getFragment() {
        Intent intent = getIntent();
        Class<? extends Fragment> fragmentClass = (Class<? extends Fragment>) intent.getSerializableExtra(Extra.CONTENT);
        Fragment fragment = createFragment(fragmentClass);
        Bundle fragmentArguments = intent.getExtras();
        fragment.setArguments(fragmentArguments);
        return fragment;
    }

    private Fragment createFragment(Class<? extends Fragment> fragmentClass) {
        try {
            Fragment fragment = fragmentClass.newInstance();
            return fragment;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
